package com.seal.commons.groovy.loader;

import com.seal.commons.groovy.GroovyLoaderException;
import com.seal.commons.groovy.model.GroovyScript;
import com.seal.commons.groovy.enums.GroovyScriptType;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;

import java.io.File;


/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2021-04-20 22:14<br/>
 * @since JDK 1.8
 */
public class GroovyBeanLoader {

    private static GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

    public Object loader(GroovyScript script){
        try {
            if(script == null) return null;
            if (GroovyScriptType.CODE == script.getType()) {
                Class cls = groovyClassLoader.parseClass(script.getCode());
                return cls.newInstance();
            }
            if (GroovyScriptType.FILE == script.getType()) {
                File file = new File(script.getPath());
                Class cls = groovyClassLoader.parseClass(file);
                return cls.newInstance();
            }
            if (GroovyScriptType.URL == script.getType()) {
                Class cls = groovyClassLoader.parseClass(new GroovyCodeSource(script.getUrl()));
                return cls.newInstance();
            }
            throw new GroovyLoaderException("groovy script type error, type:["+ script.getType() +"]");
        }catch (Exception e){
            throw new GroovyLoaderException("groovy loader exception", e);
        }
    }
}